import { initMermaid, updateMermaidTheme, presetThemes, getCurrentTheme } from './utils/mermaidConfig.js';
import { debounce } from './utils/chartUtils.js';
import { detectChartType, getThemeVariablesByChartType, getThemeVariableLabelsByChartType } from './utils/themeUtils.js';

// 编辑器功能实现
class MermaidEditor {
    constructor() {
        // 状态变量
        this.debounceRender = null;
        this.mermaid = null;
        this.isInitialized = false;
        this.currentChartType = 'default'; // 当前图表类型
        
        // 图片案例代码数组
        this.imageExamples = [
            'flowchart TD\n    A[开始] --> B[加载图片]\n    B --> C{图片格式?}\n    C -->|JPG/PNG| D[优化压缩]\n    C -->|SVG| E[矢量处理]\n    D --> F[应用滤镜]\n    E --> F\n    F --> G[渲染展示]\n    G --> H[结束]',
            'sequenceDiagram\n    participant User as 用户\n    participant Editor as 编辑器\n    participant Renderer as 渲染器\n    \n    User->>Editor: 输入图片代码\n    Editor->>Renderer: 请求渲染\n    Renderer-->>Editor: 返回SVG结果\n    Editor-->>User: 显示预览效果\n    \n    User->>Editor: 修改代码\n    Editor->>Renderer: 更新渲染\n    Renderer-->>Editor: 返回更新结果\n    Editor-->>User: 实时预览更新'
        ];
        
        // 获取DOM元素
        this._initializeElements();
    }
    
    _initializeElements() {
        // 获取DOM元素
        this.codeEditor = document.getElementById('code-editor');
        this.codeHighlight = document.getElementById('code-highlight');
        this.previewContainer = document.getElementById('chart-preview');
        this.chartPreviewWrapper = document.getElementById('chart-preview-wrapper');
        this.resizer = document.getElementById('resizer');
        this.copyCodeBtn = document.getElementById('copy-code');
        this.exportDropdown = document.getElementById('export-dropdown');
        this.exportMenu = document.getElementById('export-menu');
        this.exportSvgBtn = document.getElementById('export-svg');
        this.exportPngBtn = document.getElementById('export-png');
        this.exportPdfBtn = document.getElementById('export-pdf');
        this.backBtn = document.getElementById('back-btn');
        
        // 缩放和导览相关元素
        this.zoomInBtn = document.getElementById('zoom-in');
        this.zoomOutBtn = document.getElementById('zoom-out');
        this.miniMap = document.getElementById('mini-map');
        this.miniMapViewport = document.getElementById('mini-map-viewport');
        
        // 主题相关元素
        this.themeDropdown = document.getElementById('theme-dropdown');
        this.themeMenu = document.getElementById('theme-menu');
        this.customThemeBtn = document.getElementById('custom-theme-btn');
        this.customThemeModal = document.getElementById('custom-theme-modal');
        this.closeThemeModal = document.getElementById('close-theme-modal');
        this.resetThemeBtn = document.getElementById('reset-theme');
        this.applyCustomThemeBtn = document.getElementById('apply-custom-theme');
        
        // 背景设置相关元素（新位置）
        this.backgroundColorPicker = document.getElementById('background-color');
        this.patternOptions = document.querySelectorAll('.pattern-btn');
        
        // 颜色输入元素
        this.primaryColorInput = document.getElementById('primary-color');
        this.primaryColorText = document.getElementById('primary-color-text');
        this.primaryBorderColorInput = document.getElementById('primary-border-color');
        this.primaryBorderColorText = document.getElementById('primary-border-color-text');
        this.nodeColorInput = document.getElementById('node-color');
        this.nodeColorText = document.getElementById('node-color-text');
        this.nodeBorderColorInput = document.getElementById('node-border-color');
        this.nodeBorderColorText = document.getElementById('node-border-color-text');
        this.primaryTextColorInput = document.getElementById('primary-text-color');
        this.primaryTextColorText = document.getElementById('primary-text-color-text');
        this.textColorInput = document.getElementById('text-color');
        this.textColorText = document.getElementById('text-color-text');
        this.lineColorInput = document.getElementById('line-color');
        this.lineColorText = document.getElementById('line-color-text');
        this.linkColorInput = document.getElementById('link-color');
        this.linkColorText = document.getElementById('link-color-text');
        this.secondaryColorInput = document.getElementById('secondary-color');
        this.secondaryColorText = document.getElementById('secondary-color-text');
        this.tertiaryColorInput = document.getElementById('tertiary-color');
        this.tertiaryColorText = document.getElementById('tertiary-color-text');
        this.backgroundColorInput = document.getElementById('background-color');
        this.backgroundColorText = document.getElementById('background-color-text');
        this.clusterColorInput = document.getElementById('cluster-color');
        this.clusterColorText = document.getElementById('cluster-color-text');
        
        // 主题预览元素
        this.themePreviewNodes = document.querySelectorAll('.preview-node');
        this.themePreviewConnectors = document.querySelectorAll('.preview-connector');
        this.previewCluster = document.querySelector('.preview-cluster');
        
        // 缩放状态
        this.scale = 1;
        this.minScale = 0.1;
        this.maxScale = 5;
        this.zoomStep = 0.1;
        
        // 拖动状态
        this.isDragging = false;
        this.lastX = 0;
        this.lastY = 0;
        this.translateX = 0;
        this.translateY = 0;
    }
    
    async init() {
        // 确保DOM元素已初始化
        this._initializeElements();
        
        // 初始化防抖渲染函数
        this.debounceRender = debounce(() => this.renderChart(), 300);
        
        // 初始化Mermaid
        await this.initializeMermaid();
        
        // 从URL参数获取代码
        if (!this.loadCodeFromUrl()) {
            this.loadRandomExample();
        }
        
        // 添加事件监听器
        this.addEventListeners();
        
        // 加载保存的背景设置
        this.loadBackgroundSettings();
    }
    
    async initializeMermaid() {
        if (!window.mermaid) {
            console.error('Mermaid未加载');
            return;
        }
        
        this.mermaid = window.mermaid;
        
        // 使用统一的Mermaid配置
        initMermaid({
            startOnLoad: false,
            securityLevel: 'loose',
            renderer: 'svg'
        });
        
        this.isInitialized = true;
        
        // 如果有代码，立即渲染
        if (this.codeEditor.value.trim()) {
            this.renderChart();
        }
    }
    
    // 更新主题预览
    updateThemePreview() {
        const primaryColor = this.primaryColorInput.value;
        const nodeColor = this.nodeColorInput.value;
        const nodeBorderColor = this.nodeBorderColorInput.value;
        const primaryTextColor = this.primaryTextColorInput.value;
        const textColor = this.textColorInput.value;
        const lineColor = this.lineColorInput.value;
        const linkColor = this.linkColorInput.value;
        const clusterColor = this.clusterColorInput.value;
        
        // 更新节点样式
        this.themePreviewNodes.forEach((node, index) => {
            // 使用不同的文字颜色来区分节点，第一个节点使用主文字颜色
            const nodeTextColor = index === 0 ? primaryTextColor : textColor;
            
            node.style.backgroundColor = nodeColor;
            node.style.borderColor = nodeBorderColor;
            node.style.borderWidth = '2px';
            node.style.borderStyle = 'solid';
            node.style.color = nodeTextColor;
            node.textContent = index === 0 ? '主节点' : '节点';
            node.style.padding = '8px 12px';
            node.style.borderRadius = '4px';
            node.style.display = 'inline-block';
            node.style.margin = '5px';
            node.style.fontSize = '14px';
            node.style.fontWeight = index === 0 ? 'bold' : 'normal';
        });
        
        // 更新连接线样式
        this.themePreviewConnectors.forEach((connector, index) => {
            const color = index === 1 ? linkColor : lineColor;
            connector.style.backgroundColor = color;
            connector.style.height = '2px';
            connector.style.margin = '10px 0';
            connector.style.position = 'relative';
            connector.style.width = '30px';
            connector.style.display = 'inline-block';
            
            // 设置箭头
            connector.style.setProperty('--arrow-color', color);
        });
        
        // 更新集群样式
        if (this.previewCluster) {
            this.previewCluster.style.backgroundColor = clusterColor;
            this.previewCluster.style.padding = '15px';
            this.previewCluster.style.borderRadius = '6px';
            this.previewCluster.style.display = 'inline-block';
            this.previewCluster.style.marginRight = '15px';
        }
    }

    // 显示图表提示文档模态框
    showChartDocsModal() {
        const modal = document.getElementById('chart-docs-modal');
        if (modal) {
            modal.style.display = 'flex';
            // 根据当前图表类型显示对应的文档内容
            this.updateChartDocsContent();
            
            // 添加点击背景关闭功能
            const closeOnBackgroundClick = (e) => {
                if (e.target === modal) {
                    this.hideChartDocsModal();
                    modal.removeEventListener('click', closeOnBackgroundClick);
                }
            };
            modal.addEventListener('click', closeOnBackgroundClick);
        }
    }

    // 隐藏图表提示文档模态框
    hideChartDocsModal() {
        const modal = document.getElementById('chart-docs-modal');
        if (modal) {
            modal.style.display = 'none';
        }
    }

    // 根据当前图表类型更新文档内容
    updateChartDocsContent() {
        const chartTypeIcon = document.getElementById('chart-type-icon');
        const chartTypeName = document.getElementById('chart-type-name');
        const chartTypeDescription = document.getElementById('chart-type-description');
        const chartSyntaxContent = document.getElementById('chart-syntax-content');
        const chartParametersContent = document.getElementById('chart-parameters-content');
        const chartExampleCode = document.getElementById('chart-example-code');
        const chartTipsContent = document.getElementById('chart-tips-content');
        
        if (!window.chartDocs) return;

        // 从当前代码检测图表类型，如果没有代码则使用当前图表类型
        let currentChartType = 'default';
        if (this.codeEditor && this.codeEditor.value.trim()) {
            currentChartType = detectChartType(this.codeEditor.value) || 'default';
        } else {
            currentChartType = this.currentChartType || 'default';
        }
        
        const chartDoc = window.chartDocs[currentChartType] || window.chartDocs.default;
        
        if (chartDoc) {
            console.log(`更新图表文档内容，类型: ${currentChartType}, 标题: ${chartDoc.name}`);
            
            // 更新图表类型信息
            if (chartTypeName) chartTypeName.textContent = chartDoc.name;
            if (chartTypeDescription) chartTypeDescription.textContent = chartDoc.description;
            
            // 更新语法说明
            if (chartSyntaxContent && chartDoc.syntax) {
                const syntaxContent = typeof chartDoc.syntax === 'string' ? chartDoc.syntax : chartDoc.syntax.content || '';
                chartSyntaxContent.innerHTML = `<pre><code>${syntaxContent}</code></pre>`;
            }
            
            // 更新参数说明 - 根据不同图表类型的结构来处理
            if (chartParametersContent) {
                let parametersHtml = '<p>暂无参数说明</p>';
                
                // 处理不同类型的参数结构
                if (chartDoc.parameters && Array.isArray(chartDoc.parameters)) {
                    // 标准参数数组格式
                    parametersHtml = `
                        <ul>
                            ${chartDoc.parameters.map(param => 
                                `<li><strong>${param.name}</strong>: ${param.description}</li>`
                            ).join('')}
                        </ul>
                    `;
                } else if (chartDoc.directions || chartDoc.nodes || chartDoc.participants || chartDoc.sections || chartDoc.tasks) {
                    // 处理特殊格式的图表类型（如journey的sections、tasks等）
                    let items = [];
                    
                    if (chartDoc.directions && chartDoc.directions.items) {
                        items.push(`<h4>${chartDoc.directions.title}</h4>`);
                        items.push('<ul>' + chartDoc.directions.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    if (chartDoc.nodes && chartDoc.nodes.items) {
                        items.push(`<h4>${chartDoc.nodes.title}</h4>`);
                        items.push('<ul>' + chartDoc.nodes.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    if (chartDoc.participants && chartDoc.participants.items) {
                        items.push(`<h4>${chartDoc.participants.title}</h4>`);
                        items.push('<ul>' + chartDoc.participants.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    if (chartDoc.sections && chartDoc.sections.items) {
                        items.push(`<h4>${chartDoc.sections.title}</h4>`);
                        items.push('<ul>' + chartDoc.sections.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    if (chartDoc.tasks && chartDoc.tasks.items) {
                        items.push(`<h4>${chartDoc.tasks.title}</h4>`);
                        items.push('<ul>' + chartDoc.tasks.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    if (chartDoc.emotions && chartDoc.emotions.items) {
                        items.push(`<h4>${chartDoc.emotions.title}</h4>`);
                        items.push('<ul>' + chartDoc.emotions.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    // 处理思维导图mindmap的特殊结构
                    if (chartDoc.structure && chartDoc.structure.items) {
                        items.push(`<h4>${chartDoc.structure.title}</h4>`);
                        items.push('<ul>' + chartDoc.structure.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    if (chartDoc.nodeShapes && chartDoc.nodeShapes.items) {
                        items.push(`<h4>${chartDoc.nodeShapes.title}</h4>`);
                        items.push('<ul>' + chartDoc.nodeShapes.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    if (chartDoc.formatting && chartDoc.formatting.items) {
                        items.push(`<h4>${chartDoc.formatting.title}</h4>`);
                        items.push('<ul>' + chartDoc.formatting.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    if (chartDoc.applications && chartDoc.applications.items) {
                        items.push(`<h4>${chartDoc.applications.title}</h4>`);
                        items.push('<ul>' + chartDoc.applications.items.map(item => 
                            `<li><strong>${item.code}</strong>: ${item.desc}</li>`
                        ).join('') + '</ul>');
                    }
                    
                    parametersHtml = items.join('');
                }
                
                chartParametersContent.innerHTML = parametersHtml;
            }
            
            // 更新示例代码 - 处理不同的示例格式
            if (chartExampleCode) {
                let exampleCode = '';
                
                if (chartDoc.example) {
                    if (typeof chartDoc.example === 'string') {
                        exampleCode = chartDoc.example;
                    } else if (chartDoc.example.code) {
                        exampleCode = chartDoc.example.code;
                    }
                } else if (chartDoc.examples && chartDoc.examples.length > 0 && chartDoc.examples[0].code) {
                    exampleCode = chartDoc.examples[0].code;
                }
                
                // 只显示前几行代码，让示例更简洁
                if (exampleCode) {
                    const codeLines = exampleCode.split('\n');
                    const displayCode = codeLines.slice(0, 10).join('\n');
                    chartExampleCode.textContent = displayCode + (codeLines.length > 10 ? '\n...' : '');
                } else {
                    chartExampleCode.textContent = '暂无示例代码';
                }
            }
            
            // 更新使用提示（简化版）
            if (chartTipsContent && chartDoc.tips) {
                if (Array.isArray(chartDoc.tips)) {
                    chartTipsContent.innerHTML = `
                        <ul>
                            ${chartDoc.tips.slice(0, 5).map(tip => `<li>${tip}</li>`).join('')}
                        </ul>
                    `;
                } else {
                    chartTipsContent.innerHTML = `<p>${chartDoc.tips}</p>`;
                }
            }
        } else {
            console.warn(`未找到图表文档数据，类型: ${currentChartType}`);
            // 显示默认提示信息
            if (chartTypeName) chartTypeName.textContent = '未找到文档';
            if (chartTypeDescription) chartTypeDescription.textContent = '抱歉，暂无该图表类型的文档说明。';
            if (chartParametersContent) chartParametersContent.innerHTML = '<p>暂无参数说明</p>';
            if (chartTipsContent) chartTipsContent.innerHTML = '<p>暂无使用提示</p>';
        }
    }

    // 打开自定义主题弹窗
    openCustomThemeModal() {
        if (this.customThemeModal) {
            // 每次打开窗口时从当前主题同步颜色设置
            this.resetThemeSettings();
            this.customThemeModal.style.display = 'flex';
            
            // 根据当前图表类型更新主题设置界面
            this.updateThemeSettingsByChartType();
        }
    }
    
    /**
     * 根据图表类型更新主题设置界面
     */
    updateThemeSettingsByChartType() {
        // 获取当前图表类型的主题变量标签
        const themeLabels = getThemeVariableLabelsByChartType(this.currentChartType);
        
        // 定义所有颜色选项组
        const colorGroups = [
            { elements: [this.primaryColorInput, this.primaryColorText], key: 'primaryColor' },
            { elements: [this.primaryTextColorInput, this.primaryTextColorText], key: 'primaryTextColor' },
            { elements: [this.primaryBorderColorInput, this.primaryBorderColorText], key: 'primaryBorderColor' },
            { elements: [this.nodeColorInput, this.nodeColorText], key: 'nodeColor' },
            { elements: [this.nodeBorderColorInput, this.nodeBorderColorText], key: 'nodeBorderColor' },
            { elements: [this.textColorInput, this.textColorText], key: 'textColor' },
            { elements: [this.lineColorInput, this.lineColorText], key: 'lineColor' },
            { elements: [this.linkColorInput, this.linkColorText], key: 'linkColor' },
            { elements: [this.secondaryColorInput, this.secondaryColorText], key: 'secondaryColor' },
            { elements: [this.tertiaryColorInput, this.tertiaryColorText], key: 'tertiaryColor' },
            { elements: [this.backgroundColorInput, this.backgroundColorText], key: 'backgroundColor' },
            { elements: [this.clusterColorInput, this.clusterColorText], key: 'clusterColor' }
        ];
        
        // 显示或隐藏各个颜色选项组
        colorGroups.forEach(group => {
            const shouldShow = themeLabels.includes(group.key);
            group.elements.forEach(element => {
                if (element && element.closest('.theme-option')) {
                    element.closest('.theme-option').style.display = shouldShow ? 'flex' : 'none';
                }
            });
        });
        
        // 更新弹窗标题，显示当前图表类型
        const modalTitle = this.customThemeModal.querySelector('.modal-title');
        if (modalTitle) {
            const chartTypeNames = {
                'flowchart': '流程图',
                'sequenceDiagram': '时序图',
                'classDiagram': '类图',
                'stateDiagram': '状态图',
                'gantt': '甘特图',
                'pie': '饼图',
                'erDiagram': 'ER图',
                'default': '通用图表'
            };
            modalTitle.textContent = `自定义${chartTypeNames[this.currentChartType] || '图表'}主题`;
        }
    }
    
    // 关闭自定义主题弹窗
    closeCustomThemeModal() {
        if (this.customThemeModal) {
            this.customThemeModal.style.display = 'none';
        }
    }
    
    // 重置主题设置
    resetThemeSettings() {
        // 从当前主题获取默认颜色
        const currentThemeName = getCurrentTheme();
        const currentTheme = presetThemes[currentThemeName] || presetThemes.default;
        
        // 主要颜色
        if (this.primaryColorInput) this.primaryColorInput.value = currentTheme.themeVariables.primaryColor || '#667eea';
        if (this.primaryColorText) this.primaryColorText.value = currentTheme.themeVariables.primaryColor || '#667eea';
        
        // 边框颜色
        if (this.primaryBorderColorInput) this.primaryBorderColorInput.value = currentTheme.themeVariables.primaryBorderColor || currentTheme.themeVariables.primaryColor || '#667eea';
        if (this.primaryBorderColorText) this.primaryBorderColorText.value = currentTheme.themeVariables.primaryBorderColor || currentTheme.themeVariables.primaryColor || '#667eea';
        
        // 节点颜色
        if (this.nodeColorInput) this.nodeColorInput.value = currentTheme.themeVariables.nodeColor || currentTheme.themeVariables.primaryColor || '#667eea';
        if (this.nodeColorText) this.nodeColorText.value = currentTheme.themeVariables.nodeColor || currentTheme.themeVariables.primaryColor || '#667eea';
        if (this.nodeBorderColorInput) this.nodeBorderColorInput.value = currentTheme.themeVariables.nodeBorder || currentTheme.themeVariables.primaryBorderColor || currentTheme.themeVariables.primaryColor || '#667eea';
        if (this.nodeBorderColorText) this.nodeBorderColorText.value = currentTheme.themeVariables.nodeBorder || currentTheme.themeVariables.primaryBorderColor || currentTheme.themeVariables.primaryColor || '#667eea';
        
        // 文字颜色
        if (this.primaryTextColorInput) this.primaryTextColorInput.value = currentTheme.themeVariables.primaryTextColor || '#ffffff';
        if (this.primaryTextColorText) this.primaryTextColorText.value = currentTheme.themeVariables.primaryTextColor || '#ffffff';
        if (this.textColorInput) this.textColorInput.value = currentTheme.themeVariables.textColor || '#333333';
        if (this.textColorText) this.textColorText.value = currentTheme.themeVariables.textColor || '#333333';
        
        // 线条和连接线颜色
        if (this.lineColorInput) this.lineColorInput.value = currentTheme.themeVariables.lineColor || currentTheme.themeVariables.primaryColor || '#667eea';
        if (this.lineColorText) this.lineColorText.value = currentTheme.themeVariables.lineColor || currentTheme.themeVariables.primaryColor || '#667eea';
        if (this.linkColorInput) this.linkColorInput.value = currentTheme.themeVariables.defaultLinkColor || currentTheme.themeVariables.lineColor || currentTheme.themeVariables.primaryColor || '#667eea';
        if (this.linkColorText) this.linkColorText.value = currentTheme.themeVariables.defaultLinkColor || currentTheme.themeVariables.lineColor || currentTheme.themeVariables.primaryColor || '#667eea';
        
        // 背景颜色
        if (this.secondaryColorInput) this.secondaryColorInput.value = currentTheme.themeVariables.secondaryColor || '#f5f7fa';
        if (this.secondaryColorText) this.secondaryColorText.value = currentTheme.themeVariables.secondaryColor || '#f5f7fa';
        if (this.tertiaryColorInput) this.tertiaryColorInput.value = currentTheme.themeVariables.tertiaryColor || '#e0e0e0';
        if (this.tertiaryColorText) this.tertiaryColorText.value = currentTheme.themeVariables.tertiaryColor || '#e0e0e0';
        if (this.backgroundColorInput) this.backgroundColorInput.value = currentTheme.themeVariables.backgroundColor || '#ffffff';
        if (this.backgroundColorText) this.backgroundColorText.value = currentTheme.themeVariables.backgroundColor || '#ffffff';
        if (this.clusterColorInput) this.clusterColorInput.value = currentTheme.themeVariables.clusterBkg || currentTheme.themeVariables.secondaryColor || '#f5f7fa';
        if (this.clusterColorText) this.clusterColorText.value = currentTheme.themeVariables.clusterBkg || currentTheme.themeVariables.secondaryColor || '#f5f7fa';
        
        this.updateThemePreview();
    }
    
    // 应用自定义主题
    applyCustomTheme() {
        // 获取当前图表类型对应的主题变量映射
        const themeVariablesMap = getThemeVariablesByChartType(this.currentChartType);
        
        // 创建主题变量对象，只包含当前图表类型需要的变量
        const themeVariables = {};
        
        // 添加通用变量
        if (themeVariablesMap.primaryColor) {
            themeVariables.primaryColor = this.primaryColorInput.value;
        }
        if (themeVariablesMap.primaryTextColor) {
            themeVariables.primaryTextColor = this.primaryTextColorInput.value;
        }
        if (themeVariablesMap.primaryBorderColor) {
            themeVariables.primaryBorderColor = this.primaryBorderColorInput.value;
        }
        if (themeVariablesMap.backgroundColor) {
            themeVariables.backgroundColor = this.backgroundColorInput.value;
        }
        if (themeVariablesMap.textColor) {
            themeVariables.textColor = this.textColorInput.value;
        }
        if (themeVariablesMap.labelColor) {
            themeVariables.labelColor = this.textColorInput.value;
        }
        
        // 根据不同图表类型添加特定变量
        for (const [mermaidVar, editorVar] of Object.entries(themeVariablesMap)) {
            if (editorVar && this[`${editorVar}Input`]) {
                themeVariables[mermaidVar] = this[`${editorVar}Input`].value;
            }
        }
        
        const customTheme = {
            theme: 'default',
            themeVariables: themeVariables,
            // 确保其他必要配置被保留
            startOnLoad: false,
            securityLevel: 'loose',
            renderer: 'svg',
            flowchart: {
                useMaxWidth: false,
                htmlLabels: true
            },
            sequenceDiagram: {
                useMaxWidth: false
            },
            gantt: {
                useMaxWidth: false
            },
            classDiagram: {
                useMaxWidth: false
            }
        };
        
        // 更新Mermaid主题配置到window.mermaid
        updateMermaidTheme(customTheme);
        
        // 同时更新this.mermaid对象的配置
        if (this.mermaid) {
            this.mermaid.initialize(customTheme);
        }
        
        // 重新渲染图表
        this.renderChart();
        
        // 关闭弹窗
        this.closeCustomThemeModal();
    }
    
    loadCodeFromUrl() {
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');
        
        // 确保代码编辑器元素已初始化
        if (!this.codeEditor) {
            console.error('代码编辑器元素未初始化');
            return false;
        }
        
        if (code) {
            try {
                // 解码URL参数中的代码并设置到编辑器
                const decodedCode = decodeURIComponent(code);
                this.codeEditor.value = decodedCode;
                this.updateHighlight();
                this.debounceRender();
                console.log('从URL参数成功加载代码');
                return true;
            } catch (e) {
                console.error('解析代码参数失败', e);
                // 如果解析失败，显示随机案例
                this.loadRandomExample();
                return false;
            }
        } else {
            // 如果没有URL参数，返回false，由调用者决定是否加载随机案例
            return false;
        }
    }
    
    loadRandomExample() {
        // 随机选择一个案例代码
        const randomIndex = Math.floor(Math.random() * this.imageExamples.length);
        this.codeEditor.value = this.imageExamples[randomIndex];
        this.updateHighlight();
        this.debounceRender();
    }
    
    addEventListeners() {
        // 代码编辑器事件
        if (this.codeEditor) {
            this.codeEditor.addEventListener('input', () => {
                this.updateHighlight();
                this.debounceRender();
            });
            
            if (this.codeHighlight) {
                this.codeEditor.addEventListener('scroll', () => {
                    this.codeHighlight.scrollTop = this.codeEditor.scrollTop;
                    this.codeHighlight.scrollLeft = this.codeEditor.scrollLeft;
                });
            }
        }
        
        // 分隔条事件
        this.setupResizer();
        
        // 主题切换事件已删除
        
        // 按钮事件
        if (this.copyCodeBtn) {
            this.copyCodeBtn.addEventListener('click', () => this.copyCode());
        }

        // 图表提示文档按钮事件
        this.chartDocsBtn = document.getElementById('chart-docs-btn');
        if (this.chartDocsBtn) {
            this.chartDocsBtn.addEventListener('click', () => this.showChartDocsModal());
        }

        // 关闭图表提示文档模态框（头部关闭按钮）
        document.getElementById('close-chart-docs-modal')?.addEventListener('click', () => {
            this.hideChartDocsModal();
        });

        // 关闭图表提示文档模态框（底部关闭按钮）
        document.getElementById('close-chart-docs')?.addEventListener('click', () => {
            this.hideChartDocsModal();
        });

        // 复制示例代码按钮事件
        const copyExampleBtn = document.getElementById('copy-example-btn');
        if (copyExampleBtn) {
            copyExampleBtn.addEventListener('click', () => {
                const chartExampleCode = document.getElementById('chart-example-code');
                if (chartExampleCode) {
                    navigator.clipboard.writeText(chartExampleCode.textContent).then(() => {
                        // 显示复制成功提示
                        const originalHTML = copyExampleBtn.innerHTML;
                        copyExampleBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg>';
                        copyExampleBtn.classList.add('success');
                        
                        setTimeout(() => {
                            copyExampleBtn.innerHTML = originalHTML;
                            copyExampleBtn.classList.remove('success');
                        }, 2000);
                    }).catch(() => {
                        // 复制失败处理
                        copyExampleBtn.style.color = '#dc3545';
                        setTimeout(() => {
                            copyExampleBtn.style.color = '';
                        }, 2000);
                    });
                }
            });
        }
        
        // 导出下拉菜单交互
        if (this.exportDropdown) {
            this.exportDropdown.addEventListener('click', (e) => {
                e.stopPropagation();
                if (this.exportMenu) {
                    this.exportMenu.classList.toggle('show');
                }
            });
            
            // 点击其他区域关闭下拉菜单
            document.addEventListener('click', () => {
                if (this.exportMenu) {
                    this.exportMenu.classList.remove('show');
                }
            });
            
            // 阻止下拉菜单内点击事件冒泡
            if (this.exportMenu) {
                this.exportMenu.addEventListener('click', (e) => {
                    e.stopPropagation();
                });
            }
        }
        
        // 导出按钮点击事件
        if (this.exportSvgBtn) {
            this.exportSvgBtn.addEventListener('click', () => this.exportSvg());
        }
        if (this.exportPngBtn) {
            this.exportPngBtn.addEventListener('click', () => this.exportPng());
        }
        if (this.exportPdfBtn) {
            this.exportPdfBtn.addEventListener('click', () => this.exportPdf());
        }
        
        // 主题切换下拉菜单交互
        if (this.themeDropdown) {
            this.themeDropdown.addEventListener('click', (e) => {
                e.stopPropagation();
                if (this.themeMenu) {
                    this.themeMenu.classList.toggle('show');
                }
            });
        }
        
        // 新的背景颜色选择器事件
        if (this.backgroundColorPicker) {
            this.backgroundColorPicker.addEventListener('input', (e) => {
                const color = e.target.value;
                this.applyBackgroundColor(color);
                // 保存设置到localStorage
                localStorage.setItem('mermaidBackground', color);
            });
        }
        
        // 新的背景图案选择事件
        if (this.patternOptions.length > 0) {
            this.patternOptions.forEach(option => {
                option.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const pattern = option.getAttribute('data-pattern');
                    if (pattern) {
                        this.applyBackgroundPattern(pattern);
                        // 保存设置到localStorage
                        localStorage.setItem('mermaidBackgroundPattern', pattern);
                        
                        // 添加选中样式
                        this.patternOptions.forEach(opt => opt.classList.remove('active'));
                        option.classList.add('active');
                    }
                });
            });
        }
        
        // 主题选项点击事件
        const themeOptions = document.querySelectorAll('[data-theme]');
        themeOptions.forEach(option => {
            option.addEventListener('click', () => {
                const themeName = option.getAttribute('data-theme');
                if (themeName) {
                    // 更新Mermaid主题
                    updateMermaidTheme(themeName);
                    
                    // 重新渲染图表
                    this.renderChart();
                    
                    // 关闭下拉菜单
                    if (this.themeMenu) {
                        this.themeMenu.classList.remove('show');
                    }
                }
            });
        });
        
        // 自定义主题按钮事件
        if (this.customThemeBtn) {
            this.customThemeBtn.addEventListener('click', () => {
                this.openCustomThemeModal();
                if (this.themeMenu) {
                    this.themeMenu.classList.remove('show');
                }
            });
        }
        
        // 关闭主题弹窗按钮
        if (this.closeThemeModal) {
            this.closeThemeModal.addEventListener('click', () => this.closeCustomThemeModal());
        }
        
        // 重置主题按钮
        if (this.resetThemeBtn) {
            this.resetThemeBtn.addEventListener('click', () => this.resetThemeSettings());
        }
        
        // 应用自定义主题按钮
        if (this.applyCustomThemeBtn) {
            this.applyCustomThemeBtn.addEventListener('click', () => this.applyCustomTheme());
        }
        
        // 颜色输入事件
        const colorInputs = [
            { input: this.primaryColorInput, text: this.primaryColorText },
            { input: this.primaryBorderColorInput, text: this.primaryBorderColorText },
            { input: this.nodeColorInput, text: this.nodeColorText },
            { input: this.nodeBorderColorInput, text: this.nodeBorderColorText },
            { input: this.secondaryColorInput, text: this.secondaryColorText },
            { input: this.tertiaryColorInput, text: this.tertiaryColorText },
            { input: this.lineColorInput, text: this.lineColorText },
            { input: this.linkColorInput, text: this.edgeColorText },
            { input: this.backgroundColorInput, text: this.backgroundColorText },
            { input: this.clusterColorInput, text: this.clusterBackgroundColorText },
            { input: this.primaryTextColorInput, text: this.primaryTextColorText },
            { input: this.textColorInput, text: this.textColorText }
        ];
        
        colorInputs.forEach(({ input, text }) => {
            if (input) {
                input.addEventListener('input', () => {
                    if (text) text.value = input.value;
                    this.updateThemePreview();
                });
            }
            if (text) {
                text.addEventListener('input', () => {
                    if (input && /^#[0-9A-Fa-f]{6}$/.test(text.value)) {
                        input.value = text.value;
                        this.updateThemePreview();
                    }
                });
            }
        });
        
        // 点击其他区域关闭所有下拉菜单
        document.addEventListener('click', () => {
            if (this.exportMenu) {
                this.exportMenu.classList.remove('show');
            }
            if (this.themeMenu) {
                this.themeMenu.classList.remove('show');
            }
        });
        
        // 阻止下拉菜单内点击事件冒泡
        [this.exportMenu, this.themeMenu].forEach(menu => {
            if (menu) {
                menu.addEventListener('click', (e) => {
                    e.stopPropagation();
                });
            }
        });
        
        // 初始化主题预览
        this.updateThemePreview();
        
        // 顶部导航按钮事件
        const homeBtn = document.getElementById('home-btn');
        const docsBtn = document.getElementById('docs-btn');
        const demosBtn = document.getElementById('demos-btn');
        
        if (homeBtn) {
            homeBtn.addEventListener('click', () => window.location.href = 'index.html');
        }
        
        if (docsBtn) {
            docsBtn.addEventListener('click', () => window.location.href = 'docs/index.html');
        }
        
        if (demosBtn) {
            demosBtn.addEventListener('click', () => window.location.href = 'demos.html');
        }
        
        // 缩放按钮事件
        if (this.zoomInBtn) {
            this.zoomInBtn.addEventListener('click', () => this.zoomIn());
        }
        if (this.zoomOutBtn) {
            this.zoomOutBtn.addEventListener('click', () => this.zoomOut());
        }
        
        // 设置拖动交互
        this.setupDragInteraction();
        
        // 导览小窗视口拖动事件
        this.setupMiniMapDrag();
        
        // 立即更新高亮（DOM已加载）
        this.updateHighlight();
    }
    
    setupResizer() {
        if (!this.resizer) return;
        
        this.resizer.addEventListener('mousedown', (e) => {
            e.preventDefault();
            this.isResizing = true;
            document.body.style.cursor = 'col-resize';
            document.body.style.userSelect = 'none';
        });
        
        document.addEventListener('mousemove', (e) => {
            if (!this.isResizing) return;
            
            const container = this.resizer.parentElement;
            const containerRect = container.getBoundingClientRect();
            const offsetX = e.clientX - containerRect.left;
            const percentage = Math.max(20, Math.min(80, (offsetX / containerRect.width) * 100));
            
            // 获取代码面板和预览面板元素
            const codePanel = document.querySelector('.code-panel');
            const previewPanel = document.querySelector('.preview-panel');
            
            if (codePanel && previewPanel) {
                codePanel.style.width = `${percentage}%`;
                previewPanel.style.width = `${100 - percentage}%`;
            }
        });
        
        document.addEventListener('mouseup', () => {
            if (this.isResizing) {
                this.isResizing = false;
                document.body.style.cursor = '';
                document.body.style.userSelect = '';
            }
        });
    }
    
    updateHighlight() {
        if (!this.codeEditor || !this.codeHighlight) return;
        
        const code = this.codeEditor.value;
        this.codeHighlight.innerHTML = code
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }
    
    /**
     * 获取并更新当前图表类型
     * @param {string} code - Mermaid代码
     * @returns {string} - 当前图表类型
     */
    updateCurrentChartType(code) {
        this.currentChartType = detectChartType(code);
        return this.currentChartType;
    }
    
    async renderChart() {
        if (!this.mermaid || !this.previewContainer) {
            console.error('Mermaid或预览容器未初始化');
            return;
        }
        
        const code = this.codeEditor.value.trim();
        if (!code) {
            this.previewContainer.innerHTML = '<div class="empty-preview">请输入Mermaid代码</div>';
            this.hideMiniMap();
            return;
        }
        
        // 更新当前图表类型
        this.updateCurrentChartType(code);
        
        try {
            // 显示加载状态
            this.previewContainer.innerHTML = '<div class="loading">正在渲染图表...</div>';
            this.hideMiniMap();
            
            // 渲染Mermaid图表
            const { svg, bindFunctions } = await this.mermaid.render('mermaid-chart', code);
            
            // 显示渲染结果
            this.previewContainer.innerHTML = svg;
            
            // 绑定交互函数（如果有的话）
            if (bindFunctions) {
                bindFunctions(this.previewContainer);
            }
            
            // 更新缩放和导览
            this.resetZoom();
            this.updateMiniMap();
            
            // 更新URL参数
            this.updateUrlWithCode(code);
        } catch (error) {
            console.error('渲染图表失败:', error);
            this.previewContainer.innerHTML = `<div class="error">渲染失败: ${error.message}</div>`;
            this.hideMiniMap();
        }
    }
    
    updateUrlWithCode(code) {
        try {
            const url = new URL(window.location);
            url.searchParams.set('code', encodeURIComponent(code));
            window.history.replaceState({}, '', url);
        } catch (error) {
            console.error('更新URL失败:', error);
        }
    }
    
    copyCode() {
        if (!this.codeEditor) return;
        
        const code = this.codeEditor.value;
        if (!code.trim()) {
            alert('没有可复制的代码');
            return;
        }
        
        navigator.clipboard.writeText(code).then(() => {
            // 显示复制成功提示
            if (this.copyCodeBtn) {
                const originalText = this.copyCodeBtn.innerHTML;
                this.copyCodeBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"></path></svg> 已复制';
                setTimeout(() => {
                    this.copyCodeBtn.innerHTML = originalText;
                }, 2000);
            }
        }).catch(err => {
            console.error('复制失败:', err);
            alert('复制失败，请手动复制');
        });
    }
    
    exportSvg() {
        const svg = this.previewContainer.querySelector('svg');
        if (!svg) {
            alert('没有可导出的图表');
            return;
        }
        
        // 克隆SVG并添加样式
        const svgClone = svg.cloneNode(true);
        const computedStyles = window.getComputedStyle(svg);
        
        // 添加基础样式
        const styleElement = document.createElementNS('http://www.w3.org/2000/svg', 'style');
        styleElement.textContent = `
            svg { background-color: ${computedStyles.backgroundColor}; }
            .node rect, .node circle, .node ellipse, .node polygon, .node path {
                fill: ${computedStyles.getPropertyValue('--node-bg-color') || '#ffffff'} !important;
                stroke: ${computedStyles.getPropertyValue('--node-border-color') || '#333333'} !important;
            }
            .edgePath path, .edgeLabel {
                stroke: ${computedStyles.getPropertyValue('--edge-color') || '#333333'} !important;
                fill: ${computedStyles.getPropertyValue('--edge-color') || '#333333'} !important;
            }
        `;
        svgClone.insertBefore(styleElement, svgClone.firstChild);
        
        // 序列化SVG
        svgClone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
        const svgData = new XMLSerializer().serializeToString(svgClone);
        const blob = new Blob([svgData], {type: 'image/svg+xml;charset=utf-8'});
        this._downloadFile(blob, `mermaid-chart-${Date.now()}.svg`);
    }
    
    exportPng() {
        const svg = this.previewContainer.querySelector('svg');
        if (!svg) {
            alert('没有可导出的图表');
            return;
        }
        
        // 克隆SVG并设置样式
        const svgClone = svg.cloneNode(true);
        const styleElement = document.createElementNS('http://www.w3.org/2000/svg', 'style');
        const computedStyles = window.getComputedStyle(svg);
        styleElement.textContent = `
            svg { background-color: ${computedStyles.backgroundColor}; }
            .node rect, .node circle, .node ellipse, .node polygon, .node path {
                fill: ${computedStyles.getPropertyValue('--node-bg-color') || '#ffffff'} !important;
                stroke: ${computedStyles.getPropertyValue('--node-border-color') || '#333333'} !important;
            }
            .edgePath path, .edgeLabel {
                stroke: ${computedStyles.getPropertyValue('--edge-color') || '#333333'} !important;
                fill: ${computedStyles.getPropertyValue('--edge-color') || '#333333'} !important;
            }
        `;
        svgClone.insertBefore(styleElement, svgClone.firstChild);
        
        // 确保SVG有正确的尺寸属性
        const rect = svg.getBoundingClientRect();
        const width = rect.width;
        const height = rect.height;
        
        // 设置SVG的width和height属性
        svgClone.setAttribute('width', width);
        svgClone.setAttribute('height', height);
        svgClone.setAttribute('viewBox', `0 0 ${width} ${height}`);
        
        // 创建一个canvas元素
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // 设置canvas尺寸（提高分辨率）
        const scale = 2;
        canvas.width = width * scale;
        canvas.height = height * scale;
        ctx.scale(scale, scale);
        
        // 将SVG转换为数据URL
        svgClone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
        const svgData = new XMLSerializer().serializeToString(svgClone);
        const svgBlob = new Blob([svgData], {type: 'image/svg+xml;charset=utf-8'});
        const svgUrl = URL.createObjectURL(svgBlob);
        
        // 创建图片对象
        const img = new Image();
        img.crossOrigin = 'anonymous'; // 添加跨域属性避免canvas污染
        
        // 图片加载成功处理
        img.onload = () => {
            try {
                // 绘制背景
                ctx.fillStyle = computedStyles.backgroundColor;
                ctx.fillRect(0, 0, width, height);
                
                // 绘制图片到canvas
                ctx.drawImage(img, 0, 0, width, height);
                
                // 尝试使用toBlob导出（首选方法）
                canvas.toBlob((blob) => {
                    if (blob) {
                        this._downloadFile(blob, `mermaid-chart-${Date.now()}.png`);
                    }
                    URL.revokeObjectURL(svgUrl);
                }, 'image/png');
            } catch (error) {
                console.error('Canvas导出错误:', error);
                // 如果toBlob失败，尝试使用toDataURL作为备选方案
                try {
                    const dataUrl = canvas.toDataURL('image/png');
                    const link = document.createElement('a');
                    link.download = `mermaid-chart-${Date.now()}.png`;
                    link.href = dataUrl;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    URL.revokeObjectURL(svgUrl);
                } catch (fallbackError) {
                    console.error('Canvas导出备选方案失败:', fallbackError);
                    alert('导出PNG失败: ' + fallbackError.message);
                    URL.revokeObjectURL(svgUrl);
                }
            }
        };
        
        // 图片加载失败处理（可能是跨域问题）
        img.onerror = () => {
            console.warn('图片加载失败，可能是跨域问题，尝试直接绘制SVG到Canvas');
            try {
                // 绘制背景
                ctx.fillStyle = computedStyles.backgroundColor;
                ctx.fillRect(0, 0, width, height);
                
                // 尝试直接使用toDataURL导出
                const dataUrl = canvas.toDataURL('image/png');
                const link = document.createElement('a');
                link.download = `mermaid-chart-${Date.now()}.png`;
                link.href = dataUrl;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(svgUrl);
            } catch (error) {
                console.error('Canvas导出错误:', error);
                alert('导出PNG失败: ' + error.message);
                URL.revokeObjectURL(svgUrl);
            }
        };
        
        // 开始加载图片
        img.src = svgUrl;
    }
    
    exportPdf() {
        const svg = this.previewContainer.querySelector('svg');
        if (!svg) {
            alert('没有可导出的图表');
            return;
        }
        
        // 克隆SVG并设置样式
        const svgClone = svg.cloneNode(true);
        const computedStyles = window.getComputedStyle(svg);
        
        // 确保SVG有正确的尺寸属性
        const rect = svg.getBoundingClientRect();
        const width = rect.width;
        const height = rect.height;
        
        // 设置SVG的width和height属性
        svgClone.setAttribute('width', width);
        svgClone.setAttribute('height', height);
        svgClone.setAttribute('viewBox', `0 0 ${width} ${height}`);
        
        // 添加样式
        const styleElement = document.createElementNS('http://www.w3.org/2000/svg', 'style');
        styleElement.textContent = `
            svg { background-color: ${computedStyles.backgroundColor}; }
            .node rect, .node circle, .node ellipse, .node polygon, .node path {
                fill: ${computedStyles.getPropertyValue('--node-bg-color') || '#ffffff'} !important;
                stroke: ${computedStyles.getPropertyValue('--node-border-color') || '#333333'} !important;
            }
            .edgePath path, .edgeLabel {
                stroke: ${computedStyles.getPropertyValue('--edge-color') || '#333333'} !important;
                fill: ${computedStyles.getPropertyValue('--edge-color') || '#333333'} !important;
            }
        `;
        svgClone.insertBefore(styleElement, svgClone.firstChild);
        
        // 创建临时容器用于PDF导出
        const container = document.createElement('div');
        container.style.width = `${width}px`;
        container.style.height = `${height}px`;
        container.style.display = 'flex';
        container.style.justifyContent = 'center';
        container.style.alignItems = 'center';
        container.style.backgroundColor = computedStyles.backgroundColor;
        container.appendChild(svgClone);
        
        // 添加到body以确保正确渲染
        document.body.appendChild(container);
        
        // 根据宽高比确定PDF页面方向
        const isLandscape = width > height;
        const orientation = isLandscape ? 'landscape' : 'portrait';
        
        // 配置导出选项，确保内容适应一页并居中显示
        const opt = {
            margin: [10, 10, 10, 10],
            filename: `mermaid-chart-${Date.now()}.pdf`,
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: { 
                scale: 2,
                useCORS: true,
                logging: false
            },
            jsPDF: { unit: 'mm', format: 'a4', orientation: orientation },
            pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
        };
        
        // 导出PDF
        html2pdf().set(opt).from(container).save().then(() => {
            // 导出完成后移除临时容器
            document.body.removeChild(container);
        }).catch(error => {
            console.error('PDF导出错误:', error);
            // 移除临时容器
            document.body.removeChild(container);
            // 如果html2pdf失败，使用备选方案导出为PNG
            this.exportPdfFallback(svg);
        });
    }
    
    // PDF导出备选方案（当html2pdf失败时使用）
    exportPdfFallback(svg) {
        try {
            // 克隆SVG并设置样式
            const svgClone = svg.cloneNode(true);
            const computedStyles = window.getComputedStyle(svg);
            
            // 确保SVG有正确的尺寸属性
            const rect = svg.getBoundingClientRect();
            const width = rect.width;
            const height = rect.height;
            
            // 设置SVG的width和height属性
            svgClone.setAttribute('width', width);
            svgClone.setAttribute('height', height);
            svgClone.setAttribute('viewBox', `0 0 ${width} ${height}`);
            
            // 添加样式
            const styleElement = document.createElementNS('http://www.w3.org/2000/svg', 'style');
            styleElement.textContent = `
                svg { background-color: ${computedStyles.backgroundColor}; }
                .node rect, .node circle, .node ellipse, .node polygon, .node path {
                    fill: ${computedStyles.getPropertyValue('--node-bg-color') || '#ffffff'} !important;
                    stroke: ${computedStyles.getPropertyValue('--node-border-color') || '#333333'} !important;
                }
                .edgePath path, .edgeLabel {
                    stroke: ${computedStyles.getPropertyValue('--edge-color') || '#333333'} !important;
                    fill: ${computedStyles.getPropertyValue('--edge-color') || '#333333'} !important;
                }
            `;
            svgClone.insertBefore(styleElement, svgClone.firstChild);
            
            // 创建canvas元素
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            // 设置canvas尺寸
            canvas.width = width * 2; // 提高分辨率
            canvas.height = height * 2;
            ctx.scale(2, 2);
            
            // 将SVG转换为数据URL
            svgClone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
            const svgData = new XMLSerializer().serializeToString(svgClone);
            const svgBlob = new Blob([svgData], {type: 'image/svg+xml;charset=utf-8'});
            const svgUrl = URL.createObjectURL(svgBlob);
            
            // 创建图片对象
            const img = new Image();
            img.crossOrigin = 'anonymous'; // 添加跨域属性避免canvas污染
            img.onload = () => {
                try {
                    // 绘制背景
                    ctx.fillStyle = computedStyles.backgroundColor;
                    ctx.fillRect(0, 0, width, height);
                    
                    // 绘制图片到canvas
                    ctx.drawImage(img, 0, 0, width, height);
                    
                    // 将canvas转换为PNG并下载
                    canvas.toBlob((blob) => {
                        if (blob) {
                            this._downloadFile(blob, `mermaid-chart-${Date.now()}.png`);
                            alert('PDF导出需要在线加载库，已导出为PNG格式');
                        }
                        URL.revokeObjectURL(svgUrl);
                    }, 'image/png');
                } catch (error) {
                    console.error('Canvas导出错误:', error);
                    alert('导出PNG失败: ' + error.message);
                    URL.revokeObjectURL(svgUrl);
                }
            };
            img.onerror = () => {
                // 如果图片加载失败，尝试使用canvas.toDataURL作为备选方案
                try {
                    // 绘制背景
                    ctx.fillStyle = computedStyles.backgroundColor;
                    ctx.fillRect(0, 0, width, height);
                    
                    // 将canvas转换为PNG并下载
                    const dataUrl = canvas.toDataURL('image/png');
                    const link = document.createElement('a');
                    link.download = `mermaid-chart-${Date.now()}.png`;
                    link.href = dataUrl;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    alert('PDF导出需要在线加载库，已导出为PNG格式');
                    
                    URL.revokeObjectURL(svgUrl);
                } catch (error) {
                    console.error('Canvas导出错误:', error);
                    alert('导出PNG失败: ' + error.message);
                    URL.revokeObjectURL(svgUrl);
                }
            };
            img.src = svgUrl;
        } catch (error) {
            console.error('PDF备选导出方案错误:', error);
            alert('PDF导出失败: ' + error.message);
        }
    }
    
    // 通用文件下载方法
    _downloadFile(blob, filename) {
        const url = URL.createObjectURL(blob);
        const downloadLink = document.createElement('a');
        downloadLink.href = url;
        downloadLink.download = filename;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        
        // 清理
        setTimeout(() => {
            document.body.removeChild(downloadLink);
            URL.revokeObjectURL(url);
        }, 100);
    }
    
    // 缩放控制相关方法
    zoomIn() {
        if (this.scale < this.maxScale) {
            this.scale += this.zoomStep;
            this.applyZoom();
        }
    }
    
    zoomOut() {
        if (this.scale > this.minScale) {
            this.scale -= this.zoomStep;
            this.applyZoom();
        }
    }
    
    applyZoom() {
        if (!this.previewContainer) return;
        
        const svg = this.previewContainer.querySelector('svg');
        if (!svg) return;
        
        // 应用缩放
        svg.style.transform = `scale(${this.scale})`;
        svg.style.transformOrigin = 'center center';
        
        // 更新导览小窗视口
        this.updateMiniMapViewport();
    }
    
    resetZoom() {
        this.scale = 1;
        this.applyZoom();
    }
    
    // 拖动交互相关方法
    setupDragInteraction() {
        if (!this.previewContainer) return;
        
        const svg = this.previewContainer.querySelector('svg');
        if (!svg) return;
        
        // 鼠标按下事件
        svg.addEventListener('mousedown', (e) => {
            if (e.button !== 0) return; // 只处理左键
            this.isDragging = true;
            this.lastX = e.clientX;
            this.lastY = e.clientY;
            svg.style.cursor = 'grabbing';
            e.preventDefault();
        });
        
        // 鼠标移动事件
        document.addEventListener('mousemove', (e) => {
            if (!this.isDragging) return;
            
            const deltaX = e.clientX - this.lastX;
            const deltaY = e.clientY - this.lastY;
            
            this.translateX += deltaX;
            this.translateY += deltaY;
            
            // 应用平移
            this.applyTranslation();
            
            this.lastX = e.clientX;
            this.lastY = e.clientY;
        });
        
        // 鼠标释放事件
        document.addEventListener('mouseup', () => {
            if (this.isDragging) {
                this.isDragging = false;
                svg.style.cursor = 'grab';
            }
        });
        
        // 鼠标离开容器时停止拖动
        this.previewContainer.addEventListener('mouseleave', () => {
            if (this.isDragging) {
                this.isDragging = false;
                svg.style.cursor = 'grab';
            }
        });
        
        // 设置初始光标样式
        svg.style.cursor = 'grab';
    }
    
    applyTranslation() {
        if (!this.previewContainer) return;
        
        const svg = this.previewContainer.querySelector('svg');
        if (!svg) return;
        
        // 应用平移变换
        svg.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
        svg.style.transformOrigin = '0 0';
        
        // 更新导览小窗视口
        this.updateMiniMapViewport();
    }
    
    // 导览小窗相关方法
    updateMiniMap() {
        if (!this.miniMap || !this.previewContainer) return;
        
        const svg = this.previewContainer.querySelector('svg');
        if (!svg) {
            this.hideMiniMap();
            return;
        }
        
        // 显示导览小窗
        this.miniMap.style.display = 'block';
        
        // 清空导览小窗
        this.miniMap.innerHTML = '';
        
        // 克隆SVG并添加到导览小窗
        const miniSvg = svg.cloneNode(true);
        miniSvg.removeAttribute('id');
        miniSvg.style.maxWidth = '100%';
        miniSvg.style.maxHeight = '100%';
        this.miniMap.appendChild(miniSvg);
        
        // 创建视口元素
        const viewport = document.createElement('div');
        viewport.id = 'mini-map-viewport';
        viewport.style.position = 'absolute';
        viewport.style.border = '2px solid #007acc';
        viewport.style.backgroundColor = 'rgba(0, 122, 204, 0.2)';
        viewport.style.cursor = 'move';
        this.miniMap.appendChild(viewport);
        
        // 更新视口尺寸和位置
        this.updateMiniMapViewport();
        
        // 添加视口拖动事件
        this.setupMiniMapDrag();
    }
    
    updateMiniMapViewport() {
        if (!this.miniMap || !this.previewContainer) return;
        
        const svg = this.previewContainer.querySelector('svg');
        const viewport = document.getElementById('mini-map-viewport');
        if (!svg || !viewport) return;
        
        const containerRect = this.previewContainer.getBoundingClientRect();
        const svgRect = svg.getBoundingClientRect();
        
        // 计算视口相对于导览小窗的比例
        const scaleX = this.miniMap.clientWidth / svgRect.width;
        const scaleY = this.miniMap.clientHeight / svgRect.height;
        
        // 计算视口尺寸
        const viewportWidth = containerRect.width * scaleX;
        const viewportHeight = containerRect.height * scaleY;
        
        // 计算视口位置
        const offsetX = (-this.translateX * scaleX);
        const offsetY = (-this.translateY * scaleY);
        
        // 应用视口样式
        viewport.style.width = `${viewportWidth}px`;
        viewport.style.height = `${viewportHeight}px`;
        viewport.style.left = `${offsetX}px`;
        viewport.style.top = `${offsetY}px`;
    }
    
    setupMiniMapDrag() {
        if (!this.miniMap) return;
        
        const viewport = document.getElementById('mini-map-viewport');
        if (!viewport) return;
        
        let isDragging = false;
        let startX, startY;
        
        viewport.addEventListener('mousedown', (e) => {
            isDragging = true;
            startX = e.clientX - parseInt(viewport.style.left || 0);
            startY = e.clientY - parseInt(viewport.style.top || 0);
            e.preventDefault();
        });
        
        document.addEventListener('mousemove', (e) => {
            if (!isDragging) return;
            
            // 计算原始位置
            let x = e.clientX - startX;
            let y = e.clientY - startY;
            
            // 获取导览小窗内容区域和小方块的尺寸
            const miniMapContent = this.miniMap.querySelector('.mini-map-content');
            if (miniMapContent) {
                const contentRect = miniMapContent.getBoundingClientRect();
                const viewportRect = viewport.getBoundingClientRect();
                
                // 计算边界限制
                const maxX = contentRect.width - viewportRect.width;
                const maxY = contentRect.height - viewportRect.height;
                
                // 应用边界检查，确保小方块不超出导览小窗
                x = Math.max(0, Math.min(x, maxX));
                y = Math.max(0, Math.min(y, maxY));
            }
            
            viewport.style.left = `${x}px`;
            viewport.style.top = `${y}px`;
            
            // 更新主视图的平移
            const scaleX = this.miniMap.clientWidth / this.previewContainer.querySelector('svg').getBoundingClientRect().width;
            const scaleY = this.miniMap.clientHeight / this.previewContainer.querySelector('svg').getBoundingClientRect().height;
            
            this.translateX = -x / scaleX;
            this.translateY = -y / scaleY;
            this.applyTranslation();
        });
        
        document.addEventListener('mouseup', () => {
            isDragging = false;
        });
    }
    
    hideMiniMap() {
        if (this.miniMap) {
            this.miniMap.style.display = 'none';
        }
    }
    
    // 应用背景颜色
    applyBackgroundColor(color) {
        if (this.previewContainer) {
            // 移除所有背景颜色类
            this.previewContainer.classList.remove('bg-white', 'bg-light-gray', 'bg-gray', 'bg-black', 'bg-light-green');
            
            // 如果是预设颜色，添加对应的类
            if (color === 'white') {
                this.previewContainer.classList.add('bg-white');
                this.previewContainer.style.backgroundColor = '';
            } else if (color === 'light-gray') {
                this.previewContainer.classList.add('bg-light-gray');
                this.previewContainer.style.backgroundColor = '';
            } else if (color === 'gray') {
                this.previewContainer.classList.add('bg-gray');
                this.previewContainer.style.backgroundColor = '';
            } else if (color === 'black') {
                this.previewContainer.classList.add('bg-black');
                this.previewContainer.style.backgroundColor = '';
            } else if (color === 'light-green') {
                this.previewContainer.classList.add('bg-light-green');
                this.previewContainer.style.backgroundColor = '';
            } else {
                // 自定义颜色
                this.previewContainer.style.backgroundColor = color;
            }
        }
    }
    
    // 应用背景图案
    applyBackgroundPattern(pattern) {
        if (this.previewContainer) {
            // 移除所有背景图案类
            this.previewContainer.classList.remove('bg-pattern-dots', 'bg-pattern-lines', 'bg-pattern-grid');
            
            // 根据图案类型添加相应的类
            if (pattern === 'dots') {
                this.previewContainer.classList.add('bg-pattern-dots');
            } else if (pattern === 'lines') {
                this.previewContainer.classList.add('bg-pattern-lines');
            } else if (pattern === 'grid') {
                this.previewContainer.classList.add('bg-pattern-grid');
            } else if (pattern === 'none') {
                // none模式下不添加任何图案类，保持纯色背景
                // 已经通过上面的classList.remove实现了清除所有图案
            }
        }
    }
    
    // 加载保存的背景设置
    loadBackgroundSettings() {
        // 加载背景颜色
        const savedBackground = localStorage.getItem('mermaidBackground') || '#ffffff';
        this.applyBackgroundColor(savedBackground);
        // 更新颜色选择器的值
        if (this.backgroundColorPicker) {
            this.backgroundColorPicker.value = savedBackground;
        }
        
        // 加载背景图案
        const savedPattern = localStorage.getItem('mermaidBackgroundPattern') || 'none';
        this.applyBackgroundPattern(savedPattern);
        // 更新图案选项的选中状态
        if (this.patternOptions.length > 0) {
            this.patternOptions.forEach(option => {
                option.classList.remove('active');
                if (option.getAttribute('data-pattern') === savedPattern) {
                    option.classList.add('active');
                }
            });
        }
    }
}

// 当DOM加载完成后初始化编辑器
document.addEventListener('DOMContentLoaded', () => {
    // 初始化代码高亮容器
    const codeHighlight = document.getElementById('code-highlight');
    if (codeHighlight) {
        codeHighlight.classList.add('language-mermaid');
    }
    
    // 初始化Mermaid编辑器
    window.mermaidEditor = new MermaidEditor();
    // 初始化编辑器
    window.mermaidEditor.init();
});